import java.util.ArrayList;


public class LinkedMap {

	private  ArrayList<Integer>[] listZone;
	private int num = 0;
	@SuppressWarnings("unchecked")
	public LinkedMap(int [][] zoneMap){
		listZone = new ArrayList[zoneMap.length];
		for(int i = 0;i < listZone.length;i++){
			listZone[i] = new ArrayList<>();
		}
		
		for(int i = 0;i <zoneMap.length;i++){
			for(int j = 0;j < zoneMap[i].length;j++){
				if(zoneMap[i][j] == 1){
					listZone[i].add(j);
				}
			}
		}
	}
	
	public void printMap(){
		for(int i = 0;i < listZone.length;i++)
			for(int j:listZone[i])
				System.out.println("("+i + ","+j+")");
	}
	
	public void findCircle(){
		boolean[] visited = new boolean[listZone.length];
		ArrayList<Integer> path = new ArrayList<>();
		
		for(int i = 0;i < visited.length;i++)
			visited[i] = false;
		
		int numOfMap = 0;
outFor:	for(int i = 0;i < listZone.length;i ++){
			if(!visited[i] && listZone[i].size() != 0){
				for(int count = 0;count < visited.length;count++){
					if(visited[count] && listZone[i].contains(count)){
						visited[i] = true;
						continue outFor;
					}
				}
				num = 0;
				System.out.println("Son Map "+ ++numOfMap + ":");
				findCircle(i,visited,path);
				if(num == 0)
					System.out.println("No Circle!");
			}
		}
	}
	
	private void findCircle(int i, boolean[] visited,ArrayList<Integer> path) {
		if(path.contains(i)){
			System.out.println("     Circle " + ++num+":");
			System.out.print("         ");
			for(int count = path.indexOf(i);count < path.size();count ++){
				System.out.print(path.get(count) + "->");
			}
			System.out.println(i+"\n");
			return;
		}
		
		path.add(i);
		visited[i] = true;
		for(int j = 0;j < listZone[i].size();j++){
			findCircle(listZone[i].get(j),visited,path);
		}
		path.remove(path.size() - 1);
	}

	
	
	
	
	
	
	public static void main(String[] args){
		int zone[][] = 
		{{0,1,0,0,0},
		 {0,0,1,1,0},
		 {0,0,0,1,0},
		 {1,0,0,0,1},
		 {1,0,0,0,0}
		};
		LinkedMap m = new LinkedMap(zone);
		m.findCircle();
	}
	
}
